﻿using PayrollHR.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Payroll.BusinessLogic.CustomerManager;
using Payroll.BusinessLogic.Discounts;
using Payroll.Common.Utils;
using System.IO;
using OfficeOpenXml;
using Payroll.BusinessLogic;

namespace PayrollHR.Administration.Modules
{
    public partial class homologousControl : BasePayrollAdministrationUserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.BindData();
            }
        }
        private void BindData()
        {
            var customer = this.DiscountService.GetAllDiscount();
            gvDistributor.DataSource = customer;
            gvDistributor.DataBind();
        }
        private void Export()
        {
            List<int> List = new List<int>();
            DateTime tem = ctrlToDatePicker.SelectedDate.Value;
            string Todate = tem.ToString("yyyy-MM-dd");
            
            foreach (GridViewRow row in gvDistributor.Rows)
            {
                var cbCustomerId = row.FindControl("cbCustomerId") as CheckBox;
                bool isChecked = cbCustomerId.Checked;
                if (isChecked)
                {
                    List.Add(CommonHelper.ToInteger(gvDistributor.DataKeys[row.RowIndex].Value));
                }
            }
            string filename = String.Format("{0}_bang_tinh_doi_soat_{1}.xlsx", DateTime.Now.ToString("yyyy-MM-dd"), PayrollContext.Current.Session.EmployeeId);
            FileInfo fileInfoTemplate = new FileInfo(String.Format("{0}\\Administration\\Template\\bang_tinh_doi_soat.xlsx", Server.MapPath("~")));
            string fileInfo = String.Format("{0}\\Administration\\FileExport\\{1}", Server.MapPath("~"), filename);
            if (File.Exists(fileInfo))
                File.Delete(fileInfo);

            FileInfo filewrite = fileInfoTemplate.CopyTo(fileInfo, true);

            using (var xls = new ExcelPackage(filewrite))
            {
                ExcelWorksheet tmp_homologd = xls.Workbook.Worksheets["Template"];
                foreach (int customer_id in List)
                {
                    var discount = this.DiscountService.GetServiceByCustomerID(customer_id, Todate);
                    if (discount.Count > 0)
                    {
                        string companyName = CommonHelper.Truncate(discount[0].CustName, 31);
                        ExcelWorksheet sheetrawdata = xls.Workbook.Worksheets.Add(companyName, tmp_homologd);
                        sheetrawdata.Cells[1, 4].Value = string.Format("BẢNG ĐỐI SOÁT CÔNG NỢ THÁNG {0}/{1}", DateTime.Now.Month, DateTime.Now.Year);
                        sheetrawdata.Cells[2, 3].Value = companyName;
                        sheetrawdata.Cells[3, 3].Value = companyName;
                        sheetrawdata.Cells[4, 3].Value = string.Format("Tháng {0}/{1}", DateTime.Now.Month, DateTime.Now.Year);
                        sheetrawdata.Cells[5, 3].Value = string.Format("{0}% phí thuê bao", 55);
                        if (discount.Count > 1)
                        {
                            sheetrawdata.InsertRow(11, discount.Count - 1, 11);
                        }
                        int i = 11;
                        foreach (var info in discount)
                        {
                            sheetrawdata.Cells[i, 1].Value = (i - 10);
                            sheetrawdata.Cells[i, 2].Value = info.TaxCode;
                            sheetrawdata.Cells[i, 3].Value = info.CompanyName;
                            sheetrawdata.Cells[i, 4].Value = info.Address;
                            sheetrawdata.Cells[i, 5].Value = info.Timeline;
                            sheetrawdata.Cells[i, 6].Value = info.ServiceFee;
                            sheetrawdata.Cells[i, 7].Value = info.TokenFee;
                            sheetrawdata.Cells[i, 8].Formula = string.Format("{0}*10%", sheetrawdata.Cells[i, 6].Address);
                            sheetrawdata.Cells[i, 9].Formula = string.Format("SUM({0}:{1})", sheetrawdata.Cells[i, 6].Address, sheetrawdata.Cells[i, 8].Address);
                            sheetrawdata.Cells[i, 10].Formula = string.Format("{0}*{1}%*1.1", sheetrawdata.Cells[i, 6].Address, info.DiscountPercentage);
                            sheetrawdata.Cells[i, 11].Formula = string.Format("{0}-{1}", sheetrawdata.Cells[i, 9].Address, sheetrawdata.Cells[i, 10].Address);
                            i++;
                        }
                        //i += 1;
                        sheetrawdata.Cells[i + 1, 6].Value = string.Format("Ngày {0} tháng {1} năm {2}", tem.Day, tem.Month, tem.Year);
                        //sum
                        sheetrawdata.Cells[i, 6].Formula = string.Format("SUM({0}:{1})", sheetrawdata.Cells[11, 6].Address, sheetrawdata.Cells[i - 1, 6].Address);
                        sheetrawdata.Cells[i, 7].Formula = string.Format("SUM({0}:{1})", sheetrawdata.Cells[11, 7].Address, sheetrawdata.Cells[i - 1, 7].Address);
                        sheetrawdata.Cells[i, 8].Formula = string.Format("SUM({0}:{1})", sheetrawdata.Cells[11, 8].Address, sheetrawdata.Cells[i - 1, 8].Address);
                        sheetrawdata.Cells[i, 9].Formula = string.Format("SUM({0}:{1})", sheetrawdata.Cells[11, 9].Address, sheetrawdata.Cells[i - 1, 9].Address);
                        sheetrawdata.Cells[i, 10].Formula = string.Format("SUM({0}:{1})", sheetrawdata.Cells[11, 10].Address, sheetrawdata.Cells[i - 1, 10].Address);
                        sheetrawdata.Cells[i, 11].Formula = string.Format("SUM({0}:{1})", sheetrawdata.Cells[11, 11].Address, sheetrawdata.Cells[i - 1, 11].Address);
                        ///
                        sheetrawdata.Cells[i + 2, 5].Formula = string.Format("{0}", sheetrawdata.Cells[i, 9].Address);
                        sheetrawdata.Cells[i + 3, 5].Formula = string.Format("{0}", sheetrawdata.Cells[i, 10].Address);
                        sheetrawdata.Cells[i + 4, 5].Formula = string.Format("{0}-{1}", sheetrawdata.Cells[i + 2, 5].Address, sheetrawdata.Cells[i + 3, 5].Address);
                        sheetrawdata.Cells[i + 5, 5].Formula = string.Format("{0}", sheetrawdata.Cells[i + 4, 5].Address);
                    }
                }
                xls.Workbook.Worksheets.Delete(tmp_homologd);
                xls.Save();
                hlexport.Visible = true;
                hlexport.Text = "Save As File Export";
                hlexport.NavigateUrl = "../FileExport/" + filename;    
            }

        }
        protected void ExportButton_Click(object sender, EventArgs e)
        {
            bool Iserror = false;
            try
            {
                this.Export();
            }
            catch (Exception ex)
            {
                Iserror = true;
                ProcessException(ex);
                hlexport.Visible = false;
            }
            finally {
                if (!Iserror)
                {
                    ShowMessage("Xuất dữ liệu đối soát thành công. 'Click Save As File Export' để lưu về máy");
                }
            }
        }

        protected void gvDistributor_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvDistributor.PageIndex = e.NewPageIndex;
            this.BindData();
        }

        protected void SearchButton_Click(object sender, EventArgs e)
        {
            this.BindData();
        }
    }
}